package com.coolham.switter;

import java.util.ArrayList;
import java.util.List;

import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class WTimeLineActivity extends Activity {
	final static String TAG = "WTimeLineActivity";

	private List<Status> mListItem = new ArrayList<Status>();

	private ListView mListView;
	private ProgressBar mProgressBar;

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.v(TAG, ">>> BroadcastReceiver onReceive=" + action);
			
	        Bundle bundle = intent.getExtras();
			
			if (action.equals(Global.ACTION_MAIN_RELOAD)) {
		        int tab_id = bundle.getInt("tab_id");
		        if(tab_id == 1) {
			        Message message = new Message();
			        message.setData(bundle);
			        message.what = 1;
			        mHandler.sendMessage(message);
		        }

			}
			else{
				Log.w(TAG, "Unknown broadcast message:" + action);
			}
		}
	};

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG, ">>>handleMessage:" + msg.toString());

			Bundle data = null;
			String receiverIntent = null;
			Intent intent = null;

			switch (msg.what) {
			case 1:
				RequestTask task = new RequestTask();  
				task.execute();  
				break;
			default:
				break;
			}
		}


	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.wtimeline_view);
		
		mListView = (ListView) findViewById(R.id.wtimeline_list);
		initListView();
		
		mProgressBar = (ProgressBar) this.findViewById(R.id.wtimeline_progress_bar);
		Drawable d = this.getResources().getDrawable(R.drawable.custom_progressbar);
		mProgressBar.setProgressDrawable(d);
		mProgressBar.setProgress(50);
		mProgressBar.setIndeterminate(true);  
		
		// execute asynchronize request task 
		RequestTask task = new RequestTask();  
		task.execute();  

		// broadcast message 
		IntentFilter filter = new IntentFilter();
	    filter.addAction(Global.ACTION_MAIN_RELOAD);
	    registerReceiver(mBroadcastReceiver, filter);
		
	}
	private void initListView() {

		//setListViewData();
		
		MyAdapter adapter = new MyAdapter(this);
		
		mListView.setAdapter(adapter);
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
	
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Log.v(TAG, ">>>onItemClick");
					
					showDetailedWeibo(position);

				}
	
		});
	
			
		mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
	
						public void onCreateContextMenu(ContextMenu menu,
								View arg1, ContextMenuInfo arg2) {
							menu.setHeaderTitle("Situstion Options");
							//menu.add(0, OPT_EDIT_SITUATION, 1, "Edit Situation");
							//menu.add(0, OPT_DELETE_SITUATION, 2, "Delete Situation");
	
						}
					});
	}

	public final class ViewHolder{
		public ImageView iconView;
		public TextView titleView;
		public TextView textView;
	}
	/**
	 *  My List View Adapter
	 * 
	 * @author Jeff
	 *
	 */
	public class MyAdapter extends BaseAdapter{

		private LayoutInflater mInflater;
		
		
		public MyAdapter(Context context){
			this.mInflater = LayoutInflater.from(context);
		}
		
		public int getCount() {
			// TODO Auto-generated method stub
			return mListItem.size();
		}

		public Object getItem(int arg0) {
			
			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			ViewHolder holder = null;
			if (convertView == null) {
				
				holder = new ViewHolder();  
				
				convertView = mInflater.inflate(R.layout.weibo_items_list, null);
				holder.iconView = (ImageView)convertView.findViewById(R.id.wb_items_list_icon);
				holder.titleView = (TextView)convertView.findViewById(R.id.wb_items_list_title);
				holder.textView = (TextView)convertView.findViewById(R.id.wb_items_list_text);
				convertView.setTag(holder);
				
			}else {
				holder = (ViewHolder)convertView.getTag();
			}
				
			Status status = mListItem.get(position);
			
			holder.iconView.setBackgroundResource(R.drawable.logo);
			holder.titleView.setText(status.getUser().getScreenName());
			holder.textView.setText(status.getText());
	
			
			holder.iconView.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					View pv =  (View) v.getParent();
					int position = mListView.indexOfChild((View) v.getParent());
					//HashMap<String, Object> map = mListItem.get(position);
				}
			});
			
			/*
			convertView.setOnClickListener(new View.OnClickListener(){
				public void onClick(View v) {
				}
			});
			*/
			
			return convertView;
		}

	}
	
	class RequestTask extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			mProgressBar.setVisibility(View.VISIBLE);
			//mProgressBar.setProgress(0);  
		}

		@Override
		protected String doInBackground(String... params) {
			Log.d(TAG, ">>>DownloadTask:doInBackground");

			Weibo weibo = OAuthConstant.getInstance().getWeibo();

			weibo.setToken(OAuthConstant.getInstance().getToken(),
					OAuthConstant.getInstance().getTokenSecret());
			
			try {
				mListItem = weibo.getFriendsTimeline();
				
				StringBuilder stringBuilder = new StringBuilder("1");
				for (weibo4andriod.Status status : mListItem) {
					stringBuilder.append(status.getUser().getScreenName()
							+ "˵:" + status.getText() + "\n");
				
				}
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			return null;

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			Log.d(TAG, ">>>DownloadTask:onPostExecute");
			mProgressBar.setVisibility(View.GONE);  
			updateListView();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// Log.d(TAG, ">>>DownloadTask:onProgressUpdate:" + values[0]);
			//setProgress(values[0]);
		}
	}

	private void showDetailedWeibo(int pos) {
		Log.v(TAG, ">>>showDetailedWeibo, pos=" + pos);

		Intent intent = new Intent();
		intent.setClass(this, DetailWeiboActivity.class);

		Status status = mListItem.get(pos);

		Bundle bundle = new Bundle();
		bundle.putSerializable("status", status);
		intent.putExtras(bundle);

		startActivity(intent);

	}

	protected void updateListView() {
		MyAdapter adapter = (MyAdapter) mListView.getAdapter();
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	
}
